package dao

import (
	"context"
	"mini-app/internal/dal"
	"mini-app/internal/models"

	"192.168.1.75/go-pkg/errorx"
)

type PromotionChannel struct{}

// Add 新增推广渠道
func (PromotionChannel) Add(
	ctx context.Context,
	query *dal.Query,
	name string, // 渠道名称
	totalDevice int64, //总设备
) (channelID string, err error) {
	// 创建渠道
	pc := query.PromotionChannel
	var promotionChannelRecord models.PromotionChannel
	promotionChannelRecord.Name = name
	promotionChannelRecord.TotalDevice = totalDevice
	err = pc.WithContext(ctx).Create(&promotionChannelRecord)
	if err != nil {
		return "", errorx.New("创建推广渠道失败", -1)
	}
	return promotionChannelRecord.ID, nil
}

// Update 更新推广渠道
func (PromotionChannel) Update(
	ctx context.Context,
	query *dal.Query,
	id string, // 渠道id
	name string, // 渠道名称
	totalDevice int64, //总设备
) error {
	pc := query.PromotionChannel
	var promotionChannelRecord models.PromotionChannel
	promotionChannelRecord.Name = name
	promotionChannelRecord.TotalDevice = totalDevice
	res, err := pc.WithContext(ctx).Where(pc.ID.Eq(id)).Updates(&promotionChannelRecord)
	if err != nil || res.RowsAffected <= 0 {
		return errorx.New("渠道更新失败", -1)
	}
	return nil
}

// UpdateTotalMember 更新总会员数量
func (PromotionChannel) UpdateTotalMember(
	ctx context.Context,
	query *dal.Query,
	id string, // 渠道id
	totalMember int64, // 会员数量
) error {
	pc := query.PromotionChannel
	res, err := pc.WithContext(ctx).Where(pc.ID.Eq(id)).UpdateSimple(pc.TotalMember.Value(totalMember))
	if err != nil || res.RowsAffected <= 0 {
		return errorx.New("更新失败", -1)
	}
	return nil
}

// Delete 删除推广渠道
func (PromotionChannel) Delete(
	ctx context.Context,
	query *dal.Query,
	id string, // 渠道id
) error {
	pc := query.PromotionChannel
	res, _ := pc.WithContext(ctx).Where(pc.ID.Eq(id)).Delete(&models.PromotionChannel{})
	if res.RowsAffected <= 0 {
		return errorx.New("删除失败", -1)
	}
	return nil
}

// List 推广渠道列表
func (PromotionChannel) List(
	ctx context.Context,
	query *dal.Query,
	name string, // 渠道名称
	page, limit int, // 分页
) (list []*models.PromotionChannel, total int64, err error) {
	pc := query.PromotionChannel
	tx := pc.WithContext(ctx)
	if name != "" {
		tx = tx.Where(pc.Name.Like("%" + name + "%"))
	}
	// 获取记录总数
	total, _ = tx.Count()

	list, _ = tx.Offset(GetPageOffset(page, limit)).Limit(GetPageLimit(limit)).Find()
	return list, total, err
}

// Detail 渠道详情
func (PromotionChannel) Detail(
	ctx context.Context,
	query *dal.Query,
	id string,
) *models.PromotionChannel {
	pc := query.PromotionChannel
	detail, _ := pc.WithContext(ctx).Where(pc.ID.Eq(id)).Take()
	return detail
}

// ExistsName 渠道名称是否已存在
func (PromotionChannel) ExistsName(
	ctx context.Context,
	query *dal.Query,
	name string,
) bool {
	pc := query.PromotionChannel
	count, _ := pc.WithContext(ctx).Where(pc.Name.Eq(name)).Count()
	return count > 0
}
